import random

from django.http import JsonResponse
from django.shortcuts import render, redirect
from django_redis import get_redis_connection
from django.conf import settings

#  自定义类
from web import models
from utils.encrypt import md5
from utils import tencent
from utils.response import BaseResponse
from web.forms.account import LoginForm, SmsLoginForm, MobileForm


def login(request):
    if request.method == "GET":
        form = LoginForm()
        return render(request, "login.html", {"form": form})

    # 1.接收并获取数据(数据格式是否为空验证 -Form组件 & ModelForm组件)
    form = LoginForm(data=request.POST)
    if not form.is_valid():
        return render(request, "login.html", {"form": form})

    # role = form.cleaned_data.get("role")
    # username = form.cleaned_data.get("username")
    # password = form.cleaned_data.get("password")
    # 表单里已经加密了（forms\account）
    # password = md5(password)

    # print(role, username, password)

    # 2.去数据库校验 1管理员 2客户
    data_dict = form.cleaned_data
    role = data_dict.pop('role')
    if role == "1":
        user_object = models.Administrator.objects.filter(active=1).filter(**data_dict).first()
    else:
        user_object = models.Customer.objects.filter(active=1).filter(**data_dict).first()

    # 校验失败
    if not user_object:
        form.add_error("password", "用户名或密码有误")
        return render(request, "login.html", {'form': form})

    # 校验success 用户信息写入session+进入项目后台

    mapping = {"1": "ADMIN", "2": "CUSTOMER"}
    # 可以不做校验 form表单已经做了
    # if role not in mapping:
    #     form.add_error("role", "角色不存在")
    #     return render(request, "login.html", {'form': form})
    request.session['user_info'] = {'role': mapping[role], 'name': user_object.username, 'id': user_object.id}
    return redirect(settings.LOGIN_HOME)


def sms_send(request):
    res = BaseResponse()
    """ 发送短信 """
    # 1. 校验手机号的格式
    request.POST.get("mobile")
    form = MobileForm(data=request.POST)
    if not form.is_valid():
        res.detail = form.errors
        return JsonResponse(res.dict, json_dumps_params={"ensure_ascii": False})

    # 对应forms的 函数clean_mobile
    # mobile = form.cleaned_data['mobile']
    # role = form.cleaned_data['role']
    # if role == "1":
    #     exists = models.Administrator.objects.filter(active=1, mobile=mobile).exists()
    # else:
    #     exists = models.Customer.objects.filter(active=1, mobile=mobile).exists()
    # if not exists:
    #     res.detail = {"mobile": "手机号不存在"}
    #     return JsonResponse(res.dict, json_dumps_params={"ensure_ascii": False})

    # 2.发送短信 + 生成验证码
    # mobile = form.cleaned_data['mobile']
    # sms_code = str(random.randint(1000, 9999))
    # is_success = tencent.send_sms(mobile, sms_code)
    # if not is_success:
    #     res.detail = {"mobile": ["发送失败, 请稍等重试"]}
    #     return JsonResponse(res.dict, json_dumps_params={"ensure_ascii": False})

    # 3.将手机和验证码保存(以便于下次校验） redis->超时时间

    # conn = get_redis_connection('default')
    # conn.set(mobile, sms_code, ex=60)
    res.status = True

    return JsonResponse(res.status)


def sms_login(request):
    if request.method == "GET":
        form = SmsLoginForm()
        return render(request, "sms_login.html", {'form': form})
    res = BaseResponse()
    # print(request.POST)
    # 1.手机格式校验
    form = SmsLoginForm(data=request.POST)
    if not form.is_valid():
        res.detail = form.errors
        return JsonResponse(res.dict)

    # 2 短信验证码 + redis中的验证码 = 》 超时时间
    # mobile = form.cleaned_data['mobile']
    # code = form.cleaned_data['code']
    # role = form.cleaned_data['role']
    #
    # conn = get_redis_connection('default')
    # cache_code = conn.get(mobile)
    # if not cache_code:
    #     res.detail = {"code": ["短信验证码未发送或失效"]}
    #     return JsonResponse(res.dict)
    # if code != cache_code.decode('utf-8'):
    #     res.detail = {'code': ["短信验证码错误"]}
    #     return JsonResponse(res.dict)

    # 获取到角色电话
    role = form.cleaned_data["role"]
    mobile = form.cleaned_data["mobile"]
    # 3 登录成功 + 注册 （监测手机号是否存在）
    # -未注册 自动注册
    # -已注册 直接登录
    if role == "1":
        user_object = models.Administrator.objects.filter(active=1, mobile=mobile).first()
    else:
        user_object = models.Customer.objects.filter(active=1, mobile=mobile).first()
    if not user_object:
        res.detail = {"mobile": "[手机号不存在]"}
        return JsonResponse(res.dict)

    # 2.2 校验成功，用户信息写入session+进入项目后台
    mapping = {"1": "ADMIN", "2": "CUSTOMER"}
    request.session[settings.NB_SESSION_KEY] = {'role': mapping[role], 'name': user_object.username, 'id': user_object.id}
    res.status = True
    res.data = settings.LOGIN_HOM
    return JsonResponse(res.dict)

def logout(request):
    """注销"""
    request.session.clear()
    return redirect(settings.NB_LOGIN_URL)


def home(request):
    return render(request, "home.html")


# def level(request):
#     return render(request, "level.html")

#
# def order(request):
#     return render(request, "order.html")
#
# def order_add(request):
#     return render(request, 'order_add.html')
#
#
# def user(request):
#     return render(request, "user.html")

